﻿using System.Linq;
using System;
using System.Collections.Generic;
using Citi.Import.Util;

namespace Citi.GocAttributes.Domain
{
    public partial class FrsOu
    {
        private const string FrsOuColumnName = "C_DSMT_TN_FRSOU";
        private const string FrsOuDescriptionColumnName = "FRSOU_PN_DESCR40";
        
        //private const string FrsOuColumnName = "DSMT FRS OU";
        //private const string FrsOuDescriptionColumnName = "FRS OU LONG DESCRIPTION";

        public static readonly List<Definition<FrsOu>> Definitions = new List<Definition<FrsOu>>
            {
                new Definition<FrsOu> { ModelProperty = x => x.Code, Required = true, ColumnName = FrsOuColumnName, CustomConversionMethod = ValidateCode},
                new Definition<FrsOu> { ModelProperty = x => x.Description, MaxLength = 100, Required = true, ColumnName = FrsOuDescriptionColumnName},
            };

        private static object ValidateCode(ref FrsOu model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format(ErrorFieldNull, FrsOuColumnName);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(SelectAll<FrsOu>).LastOrDefault(x => x.Code == int.Parse(value));

            if (domain != null)
            {
                model = domain;
                model.LastUpdate = DateTime.Now;
                return Conversion.Validation.Validated;
            }

            model.LastUpdate = DateTime.Now;
            model.ReferenceDate = DateTime.Today;
            return int.Parse(value);
        }

        public static void Save(IEnumerable<FrsOu> frsOus)
        {
            var toSave = frsOus.Distinct(new FrsOuComparer()).Where(x => x != null && x.Id == 0).ToList();

            if (toSave.Any())
                toSave.First().Save(toSave, 100);

            CacheFacade.Clear(typeof(FrsOu));
        }

        public FrsOu SelectByCode(int code)
        {
            return SelectAll<FrsOu>().FirstOrDefault(x => x.Code == code);
        }
    }

    public class FrsOuComparer : IEqualityComparer<FrsOu>
    {
        public bool Equals(FrsOu x, FrsOu y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Code == y.Code && x.Id == y.Id;
        }

        public int GetHashCode(FrsOu item)
        {
            if (ReferenceEquals(item, null)) return 0;

            var hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            var hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
